<?php

namespace app\common\helper;

class Tree
{
    /**
     * 生成树型结构所需修饰符号，可以换成图片
     * @var array
     */
    public static $icon = array('│', '├');
    public static $nbsp = "&nbsp;";
    /**
     * 主键名称
     * @var string
     */
    private static $primary = 'id';
    /**
     * 父键名称
     * @var string
     */
    private static $parentId = 'parentId';
    /**
     * 子节点名称
     * @var string
     */
    private static $child = 'child';

    /**
     * 修改主键名称、父键名称、子节点名称
     * @param string $primary
     * @param string $parentId
     * @param string $child
     */
    public static function setConfig($primary = '', $parentId = '', $child = '')
    {
        if (!empty($primary)) self::$primary = $primary;
        if (!empty($parentId)) self::$parentId = $parentId;
        if (!empty($child)) self::$child = $child;
    }

    /**
     * 生成Tree
     * @param $data
     * @param int $index
     * @param string $key
     * @return array
     */
    public static function makeTree(&$data, $index = 0, $key = 'child')
    {
        $childs = self::findChild($data, $index);
        if (empty($childs)) {
            return $childs;
        }
        foreach ($childs as $k => &$v) {
            if (empty($data)) break;
            $child = self::makeTree($data, $v[self::$primary], $key);
            if (!empty($child)) {
                $v[$key] = $child;
            }
        }
        unset($v);
        return $childs;
    }

    /**
     * 查找子类
     * @param array $data
     * @param number $index
     * @return array
     */
    public static function findChild(&$data, $index)
    {
        $childs = [];
        foreach ($data as $k => $v) {
            if ($v[self::$parentId] == $index) {
                $childs[] = $v;
                unset($v);
            }
        }
        return $childs;
    }
}